package com.mec.web.y2012.coreservlet;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.mec.beans.y2012.coreservlet.Catalog;
import com.mec.beans.y2012.coreservlet.ItemOrder;

public class ShoppingCart {
	
	private ArrayList<ItemOrder> itemsOrdered;
	
	public ShoppingCart(){
		itemsOrdered = new ArrayList<ItemOrder>();
	}
	
	//
	public List<ItemOrder> getItemsOrdered(){
		return itemsOrdered;
	}
	
	public synchronized void addItem(String itemId){
		for(ItemOrder item : itemsOrdered){
			if(item.getItem().getItemId().equals(itemId)){
				item.incrementNumItems();
				return;
			}
		}
		//
		ItemOrder newOrder = new ItemOrder(Catalog.getItem(itemId));
		itemsOrdered.add(newOrder);
	}
	
	public synchronized void setNumOrdered(String itemId, int numOrdered){
		for(ItemOrder item : itemsOrdered){
			if(itemId.equals(item.getItem().getItemId())){
				if(numOrdered <= 0){
					itemsOrdered.remove(item);
				}else{
					item.setNumItems(numOrdered);
				}
				//
				return;
			}
		}
		//
		ItemOrder newOrder = new ItemOrder(Catalog.getItem(itemId));
		itemsOrdered.add(newOrder);
	}
	
	private static final Logger logger = 
			Logger.getLogger(ShoppingCart.class);
}
